package com.algorithm;

/**
 * 项目名称: java_algorithm
 * @ClassName BinarySearch
 * @Description
 * @Author huipanxing huipanxing@chinasofti.com   @Date 2021/7/22 8:35
 */
public class BinarySearch {

    public static int search(int[] arr, int n) {
        int left = 0;
        int right = arr.length - 1;
        int i = searchTemp(left, right, arr, n);
        return i;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1, 4, 6, 8,9,11,12};
        int search = search(arr, 9);
        System.out.println(search);
    }

    public static int searchTemp(int left, int right, int[] arr, int n) {
        int index = (left + right) / 2;
        if (left > right) {
            return -1;
        }
        if (n == arr[index]) {
            return index;
        } else if (n > arr[index]) {
            left = index + 1;
            return searchTemp(left, right, arr, n);
        } else {
            right = index - 1;
            return searchTemp(left, right, arr, n);
        }
    }
}
